﻿using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Mvc;

namespace Knife.Core.Model
{
    public class Result : JsonResult
    {
        public int code { set; get; }
        public string msg { set; get; }
        private Hashtable data;
        public Result()
        {
            data = new Hashtable();
            code = 0;
            msg = "执行成功";
        }
        public static Result Success()
        {
            Result result = new Result();
            result.code = 0;
            result.msg = "执行成功";
            return result;
        }
        public static Result Fail()
        {
            Result result = new Result();
            result.code = -1;
            result.msg = "执行失败";
            return result;
        }
        public Result Add(string Key, Object Value)
        {
            if (!data.Contains(Key))
            {
                data.Add(Key, Value);
            }
            else
            {
                data[Key] = Value;
            }
            return this;
        }
        public Object Get(string Key)
        {
            return data[Key];
        }
        public override void ExecuteResult(ControllerContext context)
        {
            Hashtable result = new Hashtable();
            result.Add("code", code);
            result.Add("msg", msg);
            result.Add("data", data);
            var json = JsonConvert.SerializeObject(result,
                Formatting.Indented,
                new JsonSerializerSettings
                {
                    DateFormatString = "yyyy-MM-dd HH:mm:ss"
                }
                );
            context.HttpContext.Response.Write(json);
        }
    }
}
